package com.geline.web.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.geline.cloud.core.BaseSessionService;
import com.geline.cloud.util.StringUtils;
import com.geline.web.annotation.ValidUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 删除接口检验登录用户是否为创建人
 * 使用方式：
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ValidUserInterceptor()).addPathPatterns("/**");
     }
 *
 * @author: mx
 * @date: 2024-06-22 16:21
 */
@Slf4j
public class ValidUserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            ValidUser validUser = method.getAnnotation(ValidUser.class);
            if(validUser != null){

                MethodParameter[] parameters = handlerMethod.getMethodParameters();
                for (int i = 0; i < parameters.length; i++) {
                    MethodParameter parameter = parameters[i];
                    PathVariable variable = parameter.getParameterAnnotation(PathVariable.class);
                    if(variable!=null){
                        String paraName = parameter.getParameter().getName();
                        Map<String, String> pathVars = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
                        String ids = pathVars.get(paraName);
                        if(StrUtil.isNotBlank(ids)){
                            handleValidUser(ids, validUser);
                        }
                        break;
                    }
                }
            }
        }
        return true;
    }

    private void handleValidUser(String ids, ValidUser validUser){
        //获取删除的所有id
        List<Object> idList = Arrays.asList(ids.split(","));
        for(Object id : idList){
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("select count(*) from %s", validUser.table()));
            String createBy = validUser.createBy();
            Serializable userId = getSessionService().getUserId();
            if(StrUtil.isNotBlank(createBy)){
                sb.append(String.format(" where id=%s and %s=%s", StringUtils.quotaMark(id), createBy, StringUtils.quotaMark(userId)));
            }else {
                throw new RuntimeException("can not find @ValidUser : createBy !");
            }
            Long number = getJdbcTemplate().queryForObject(sb.toString(), Long.class);
            if(number==null || number==0){
                throw new RuntimeException(validUser.errorMessage());
            }
        }
    }

    public JdbcTemplate getJdbcTemplate() {
        return SpringUtil.getBean(JdbcTemplate.class);
    }

    public BaseSessionService getSessionService() {
        return SpringUtil.getBean(BaseSessionService.class);
    }
}
